#include "archiveinstream.h"

ArchiveInStream::ArchiveInStream(const QString &filename)
{
    mFileInfo = QFileInfo(filename);
    mFile = new QFile(filename);
    if (!mFile->open(QIODevice::ReadOnly)) return;
}

ArchiveInStream::~ArchiveInStream()
{
    delete mFile;
}

wstring ArchiveInStream::GetExt() const
{
    // until lib7zip supports filetype detection by header
    // if (mFileInfo.suffix() == "cbr") return QString("rar").toStdWString();
    // if (mFileInfo.suffix() == "cbz") return QString("zip").toStdWString();
    return mFileInfo.suffix().toStdWString();
}

int ArchiveInStream::Read(void *data, unsigned int size, unsigned int *processedSize)
{
    if (!mFile->isOpen()) return 1;
    qint64 readsize = mFile->read(static_cast<char *>(data), size);
    if (readsize <= 0) return 1;
    *processedSize = readsize;
    return 0;
}

int ArchiveInStream::Seek(long long offset, unsigned int seekOrigin, unsigned long long *newPosition)
{
    if (!mFile->isOpen()) return 1;
    qint64 pos = 0;
    if (seekOrigin == SEEK_SET) pos = offset;
    if (seekOrigin == SEEK_CUR) pos = mFile->pos() + offset;
    if (seekOrigin == SEEK_END) pos = mFileInfo.size() + offset;

    if (!mFile->seek(pos)) return 1;
    if (newPosition) *newPosition = mFile->pos();
    return 0;
}

int ArchiveInStream::GetSize(unsigned long long *size)
{
    if (size) *size = mFile->size();
    return 0;
}
